<?php

namespace App\Library\Zip;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Enum\BaseCodeEnum;

class ZipOperate
{
    public static function unzip(string $filePath, string $path): bool
    {
        if (empty($path) || empty($filePath)) {
            return false;
        }

        $zip = new \ZipArchive();
        if ($zip->open($filePath) != true) {
            throw new BaseException(BaseCodeEnum::ERR_ZIP_OPEN,
                BaseCodeEnum::CODE_TEXT[BaseCodeEnum::ERR_ZIP_OPEN] . ':' . $filePath);
        }

        $fileNum = $zip->numFiles;
        for ($i = 0; $i < $fileNum; $i++) {
            $statInfo = $zip->statIndex($i, \ZipArchive::FL_ENC_RAW);
            $zip->renameIndex($i, iconv('GBK', 'utf-8//IGNORE', $statInfo['name']));
        }
        $zip->close();
        $zip->open($filePath);

        $zip->extractTo($path);
        $zip->close();

        return true;
    }
}
